/*
  Copyright 2012 Sergey Ostanin

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/

package ru.irenproject.matchQuestion;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import org.apache.commons.lang3.Validate;

import ru.irenproject.FormulationSupplier;
import ru.irenproject.Question;
import ru.irenproject.TestCheck;
import ru.irenproject.pad.Pad;
import ru.irenproject.store.AbstractThing;
import ru.irenproject.store.Event;
import ru.irenproject.store.Stash;

import com.google.protobuf.ByteString;

public final class MatchQuestion extends AbstractThing
    implements Question, FormulationSupplier {
  public enum ChangeEvent implements Event { INSTANCE }

  public static final int MAX_ROWS = 50;

  @Stash private MatchQuestionProtos.MatchQuestion.Builder $;

  @Inject MatchQuestion() {}

  @Override protected void initialize() {
    Pad formulation = store().create(Pad.class);
    $.setFormulation(formulation.id());
  }

  @Override public Pad formulation() {
    return get($.getFormulation(), Pad.class);
  }

  public List<Pad> leftPadList() {
    return store().getBatch($.getLeftList(), Pad.class);
  }

  public List<Pad> rightPadList() {
    return store().getBatch($.getRightList(), Pad.class);
  }

  public int rightPadCount() {
    return $.getRightCount();
  }

  private void insertRightPad(Pad pad, int index) {
    List<ByteString> ids = new ArrayList<>($.getRightList());
    ids.add(index, pad.id());
    $.clearRight().addAllRight(ids);
    post(ChangeEvent.INSTANCE);
  }

  public Pad[] addPair() {
    TestCheck.input(rightPadCount() < MAX_ROWS);

    Pad rightPad = store().create(Pad.class);
    insertRightPad(rightPad, $.getLeftCount());

    Pad leftPad = store().create(Pad.class);
    $.addLeft(leftPad.id());
    post(ChangeEvent.INSTANCE);

    return new Pad[] { leftPad, rightPad };
  }

  public Pad addDistractor() {
    TestCheck.input(rightPadCount() < MAX_ROWS);

    Pad res = store().create(Pad.class);
    $.addRight(res.id());
    post(ChangeEvent.INSTANCE);

    return res;
  }

  public void deleteRow(int index) {
    checkRowIndex(index);
    if (index < $.getLeftCount()) {
      deleteLeftPad(index);
    }
    deleteRightPad(index);
  }

  private void checkRowIndex(int index) {
    TestCheck.input(index >= 0);
    TestCheck.input(index < rightPadCount());
  }

  private void deleteLeftPad(int index) {
    List<ByteString> ids = new ArrayList<>($.getLeftList());
    ids.remove(index);
    $.clearLeft().addAllLeft(ids);
    post(ChangeEvent.INSTANCE);
  }

  private void deleteRightPad(int index) {
    List<ByteString> ids = new ArrayList<>($.getRightList());
    ids.remove(index);
    $.clearRight().addAllRight(ids);
    post(ChangeEvent.INSTANCE);
  }

  public void moveRow(int index, boolean forward) {
    checkRowIndex(index);
    int newIndex = index + (forward ? 1 : -1);
    checkRowIndex(newIndex);
    TestCheck.input(
        (isDistractorRow(index) && isDistractorRow(newIndex))
        ||
        (!isDistractorRow(index) && !isDistractorRow(newIndex))
    );
    swapRightPads(index, newIndex);
    if (!isDistractorRow(index)) {
      swapLeftPads(index, newIndex);
    }
  }

  private boolean isDistractorRow(int index) {
    return index >= $.getLeftCount();
  }

  private void swapLeftPads(int index1, int index2) {
    ByteString temp = $.getLeft(index1);
    $.setLeft(index1, $.getLeft(index2));
    $.setLeft(index2, temp);
    post(ChangeEvent.INSTANCE);
  }

  private void swapRightPads(int index1, int index2) {
    ByteString temp = $.getRight(index1);
    $.setRight(index1, $.getRight(index2));
    $.setRight(index2, temp);
    post(ChangeEvent.INSTANCE);
  }

  public boolean hasPairLimit() {
    return $.hasPairLimit();
  }

  public int pairLimit() {
    Validate.isTrue(hasPairLimit());
    return $.getPairLimit();
  }

  public void setPairLimit(int value) {
    TestCheck.input(value >= 1);
    TestCheck.input(value <= MAX_ROWS);
    $.setPairLimit(value);
    post(ChangeEvent.INSTANCE);
  }

  public void clearPairLimit() {
    $.clearPairLimit();
    post(ChangeEvent.INSTANCE);
  }

  public boolean hasDistractorLimit() {
    return $.hasDistractorLimit();
  }

  public int distractorLimit() {
    Validate.isTrue(hasDistractorLimit());
    return $.getDistractorLimit();
  }

  public void setDistractorLimit(int value) {
    TestCheck.input(value >= 0);
    TestCheck.input(value <= MAX_ROWS);
    $.setDistractorLimit(value);
    post(ChangeEvent.INSTANCE);
  }

  public void clearDistractorLimit() {
    $.clearDistractorLimit();
    post(ChangeEvent.INSTANCE);
  }

  public boolean hasDefaultOptions() {
    return !hasPairLimit() && !hasDistractorLimit();
  }

  @Override public void setDefaults(String initialText) {
    formulation().appendText(initialText);
  }
}
